<?

/***************************************************************************
 Jupiter Content System @ Jupiterportal.com
 Copyright (C) 2005 Cosmin Flavius (highstrike@gmail.com)

 This program is free software; you can redistribute it and/or
 modify it under the terms of the GNU General Public License
 as published by the Free Software Foundation; either version 2
 of the License, or (at your option) any later version.

 More Info About The Licence At http://www.gnu.org/copyleft/gpl.html
****************************************************************************/

//-----------------------------------------------------------------
//  Define the wamis_DB class
//-----------------------------------------------------------------

class wamis_DB
{
	var $db = array();
	var $link_id, $query_id, $query=FALSE, $sqlr;

	var $failed = FALSE;
	var $debug = FALSE;
	var $debugtext = array();
	var $link_time;
	var $emsg;

	function wamis_DB($db_name,$user,$pass,$host="localhost")
	{
		$this->db=array('name'=>$db_name,'user'=>$user,'pass'=>$pass,'host'=>$host);
	}

	function record_error()
	{
		$this->failed=TRUE;
		if($this->debug)
		{
			$this->debugtext[]="ERROR: ".mysql_error();
			if($this->query)
				$this->query="FAILED: ".$query;
		}
	}

	function connect($persistent=false)
	{
		$this->failed=FALSE;
		$this->db['pers']=$persistent;
	
		if($persistent)
			$this->link_id=mysql_pconnect($this->db['host'],$this->db['user'],$this->db['pass']);
		else
			$this->link_id=mysql_connect($this->db['host'],$this->db['user'],$this->db['pass']);

		mysql_select_db($this->db['name']) or $this->record_error();

		//if($this->debug)
		//{
			list($usec, $sec) = explode(" ", microtime()); // measure connection time ( or script time if DB was linked at the beginning of the script
			$this->link_time=(float)$usec+(float)$sec;
		//}
		return !$this->failed; // false if failed connection
	}

	function disconnect()
	{
		$this->freeResult();
		if($this->db['pers'])
			mysql_close($this->link_id);
	
		if($this->debug)
		{
			list($usec, $sec) = explode(" ", microtime());
			$this->link_time=(float)$usec+(float)$sec-$this->link_time;
			$this->debugtext[]="END Connection: ".(string)$this->link_time." sec";
		}
	}

	function query($query)
	{
		$this->freeResult();

		$this->sqlr=mysql_query($query) or $this->record_error();
		//if($this->debug) // debug mode ( records queries )
			$this->debugtext[]="$query";
	
		return $this->sqlr;
	}

	function getRow()
	{
		if(is_resource($this->sqlr))
			return mysql_fetch_assoc($this->sqlr);
		return FALSE;
	}

	function freeResult()
	{
		if(isset($this->sqlr)&&is_resource($this->sqlr))
		{
			mysql_free_result($this->sqlr);
			unset($this->sqlr);
		}
	}

	function getLine($query,$id=FALSE)
	{
		if($id===FALSE)
			$this->query($query);
		else
			$this->query($query." WHERE `id`='$id'");
		if(is_resource($this->sqlr))
		{
			$line=mysql_fetch_assoc($this->sqlr);
			$this->freeResult();
			return $line;
		}
		return FALSE;
	}

	function getTable($query,$useid=FALSE)
	{
		$table=array();
		if($this->query($query)==FALSE) return FALSE;
		while($line=mysql_fetch_assoc($this->sqlr))
		{
			if($useid)
				$table[$line['id']]=$line;
			else
				$table[]=$line;
		}
		return $table;	
	}

    function insertRow ($table, $array)
	{
        if (count($array) == 0)
            exit;
        
        $comma = "";
        $listofvalues = "";
        $listofelements = "";
        
        foreach($array as $elem=>$value)
        {
            $listofelements .= "$comma`$elem`";
            
            if ($value === null)
                $listofvalues .= "{$comma}NULL";
            else
            {
                $value = mysql_escape_string($value);
                $listofvalues .= "$comma'$value'";
            }
            
            $comma = ',';
        };
        
        $query = "INSERT HIGH_PRIORITY INTO $table (".$listofelements.") ".
        "VALUES(".$listofvalues.")";
        
        $this->query("$query");
    }
    
    function duplicateRow ($table, $array, $condition)
	{
        if (count($array) == 0)
            exit;
        
        $comma = "";
        $listofvalues = "";
        
        $original = $this->getLine("SELECT * FROM $table WHERE $condition");
        
        foreach($original as $key=>$value)
        {
            if (array_key_exists($key, $array))
                $listofvalues .= "$comma'{$array[$key]}'";
            else
                $listofvalues .= "$comma`$key`";
            
            $comma = ",";
        }
        
        $query = "INSERT HIGH_PRIORITY INTO $table (SELECT $listofvalues FROM ".
                 "$table WHERE $condition)";
        
        $this->query("$query");
    }
    
    function updateRow ($table, $array, $condition)
    {
        if (count($array) == 0)
            exit;
        
        $q = "UPDATE $table SET";
        $comma = "";
        
        foreach($array as $index=>$value)
        {
            if ($value == NULL)
                $q .= "$comma `$index` = NULL";
            else
                $q .= "$comma `$index` = '".mysql_escape_string($value)."'";
            
            $comma = ",";
        }
        
        $q .= " WHERE $condition";
        $this->query($q);
    }
    
    function deleteRow($table,$condition,$single=true)
	{
		$q="DELETE FROM $table WHERE $condition".($single?" LIMIT 1":"");
		$this->query($q);
	}

	function getInfo_tableStatus($tablename,$what_to_get='all')
	{
		$line=$this->getLine("SHOW TABLE STATUS LIKE '$tablename'");

		switch($what_to_get)
		{
			case 'all': return array('rows'=>$line['Rows'],'autoinc'=>$line['Auto_increment']);
			case 'rows': return $line['Rows'];
			case 'autoinc':	return $line['Auto_increment'];
		}
	}

	function getInfo_countRows($tablename, $condition = false, $rename = false, 
                               $distinct = false)
	{
        if ($rename) $as = "AS `$rename`";
        else $as = "";
        
        if ($distinct) $c = "DISTINCT `$distinct`";
        else $c = "*";
        
		if ($condition)
            $line = $this->getLine("SELECT COUNT($c) FROM `$tablename` $as ".
            "WHERE $condition");
		else
            $line = $this->getLine("SELECT COUNT($c) FROM `$tablename` $as");
		
		return $line['COUNT('.$c.')'];
	}
}

//-----------------------------------------------------------------
//  Start Interface
//-----------------------------------------------------------------

@$db=new wamis_DB("$database_name","$database_username","$database_password","$database_server");

function DB_initialize($debug=false)
{
	global $db;

	$db->debug=$debug;
	$db->connect();
}

function DB_shutdown()
{
	global $db;

	$db->disconnect();
	if($db->debug)
	{
		?>
			<div id='jupiterwrapper'>
			<table class='main' cellspacing='1' cellpadding='4'>
			<tr class='head'><td colspan='2'>DB Debug</td></tr>
			<tr class='bottom'><td align='center'>#</td><td>Query</td></tr>
			<? foreach($db->debugtext as $idx=>$row) echo "<tr class='con1'><td align='center'>$idx</td><td>$row</td></tr>"; ?>
			</table></div>
		<?
	}
}

?>